package xyz.naokeziteng.leetcode;

import java.util.Arrays;

//875题: 爱吃香蕉的珂珂
public class KokoEatingBananas {

    public int minEatingSpeed(int[] piles, int h) {
        if (piles.length == 0) {
            return 0;
        }
        int l = 1;
        int r = Arrays.stream(piles).max().getAsInt();
        if (piles.length == h) {
            return r;
        }
        int result = 0;
        while (l <= r) {
            int mid = l + (r - l) / 2;
            int ht = eatingTime(piles, mid);
            if(ht < 0) {
                break;
            }else if (ht <= h) {
                result = mid;
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        return result;
    }

    private int eatingTime(int[] piles, int k) {
        int result = 0;
        for (int p : piles) {
            result += p % k == 0 ? p / k : p / k + 1;
        }
        return result;
    }

    public long getTime(int[] piles, int speed) {
        long time = 0;
        for (int pile : piles) {
            int curTime = (pile + speed - 1) / speed;
            time += curTime;
        }
        return time;
    }

    public static void main(String[] args) {
        KokoEatingBananas keb = new KokoEatingBananas();
        int[] piles = {805306368, 805306368, 805306368};
        int h = 1000000000;
        System.out.println(keb.minEatingSpeed(piles, h));
    }


}
